package com.audaque.springboot.foshanupload.reactor.webfluxdemo.service.impl;

/**
 * @author zgb
 * @desc ...
 * @date 2023-07-24 22:40:11
 */

import com.audaque.springboot.foshanupload.reactor.webfluxdemo.service.iface.UserMongodbService;
import com.audaque.springboot.foshanupload.reactor.webfluxdemo.model.pojo.UserMongodb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * 用户服务实现类.
 *
 * @author zgb
 * @date 2021-05-08 16:01
 */
@Service
public class UserMongodbServiceImpl implements UserMongodbService {

    private static final Logger logger = LoggerFactory.getLogger(UserMongodbServiceImpl.class);

    @Autowired
    private ReactiveMongoTemplate mongoTemplate;

    @Override
    public Mono<String> addUser(UserMongodb params) {
        UserMongodb userMongodbEntity = new UserMongodb();
        userMongodbEntity.setUid(params.getUid());
        userMongodbEntity.setUsername(params.getUsername());
        userMongodbEntity.setSex(params.getSex());
        userMongodbEntity.setCreatedTime(System.currentTimeMillis());
        return mongoTemplate.insert(userMongodbEntity).flatMap(userMongodb -> Mono.just(userMongodb.getId()));
    }

    @Override
    public Mono<String> deleteUser(String id) {
        Query query = Query.query(Criteria.where(UserMongodb._id).is(id));
        return mongoTemplate.findAndRemove(query, UserMongodb.class).flatMap(userMongodb ->
                Mono.just(id)
        );
    }

    @Override
    public Mono<String> editUser(UserMongodb params) {
        Query query = Query.query(Criteria.where(UserMongodb._id).is(params.getId()));
        Update update = new Update()
                .set(UserMongodb._sex, params.getSex())
                .set(UserMongodb._username, params.getUsername())
                .set(UserMongodb._updatedTime, System.currentTimeMillis());
        return mongoTemplate.updateFirst(query, update, UserMongodb.class).flatMap(user -> Mono.just(params.getId()));
    }

    @Override
    public Mono<UserMongodb> queryUserById(String id) {
        Query query = Query.query(Criteria.where(UserMongodb._id).is(id));
        return mongoTemplate.findOne(query, UserMongodb.class).flatMap(userMongodb -> {
            UserMongodb userMongodbInfo = new UserMongodb();
            userMongodbInfo.setUid(userMongodb.getUid());
            userMongodbInfo.setId(userMongodb.getId());
            userMongodbInfo.setSex(userMongodb.getSex());
            userMongodbInfo.setUsername(userMongodb.getUsername());
            return Mono.just(userMongodbInfo);
        });
    }


}
